package view.game
{
	import base.components.FileUpload;
	import base.components.LinkedLabel;
	
	import business.GameDelegate;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	
	import model.AppCons;
	import model.ModelLocator;
	
	import mx.collections.ArrayCollection;
	import mx.collections.XMLListCollection;
	import mx.containers.HBox;
	import mx.containers.VBox;
	import mx.controls.Alert;
	import mx.controls.ComboBox;
	import mx.controls.LinkButton;
	import mx.controls.TextInput;
	import mx.controls.dataGridClasses.DataGridColumn;
	import mx.core.IFlexDisplayObject;
	import mx.events.CloseEvent;
	import mx.events.CollectionEvent;
	import mx.events.CollectionEventKind;
	import mx.events.ItemClickEvent;
	import mx.events.PropertyChangeEvent;
	import mx.managers.PopUpManager;
	import mx.rpc.Fault;
	import mx.rpc.events.FaultEvent;
	
	import util.LogUtil;
	
	[Bindable]
	public class GameBasicClass extends VBox
	{
		public var contentTypesSrc:XML;
		public var editorTypesSrc:XML;
		public var fightTypesSrc:XML;
		public var gameTypesSrc:XML;
		public var screenTypesSrc:XML;
		public var payTypesSrc:XML;
		public var countrysSrc:XML;
		public var newGameTypesSrc:XML;
		public var contentTypes:XMLListCollection;
		public var editorTypes:XMLListCollection;
		public var fightTypes:XMLListCollection;
		public var gameTypes:XMLListCollection;
		public var screenTypes:XMLListCollection;
		public var payTypes:XMLListCollection;
		public var countrys:XMLListCollection;
		public var newGameTypes:XMLListCollection;
		
		public var games:ArrayCollection;
		public var page:int;
		public var pagecnt:int;
		public var pageVolume:int;
		public var pageIndices:Array;
			
		public var cmEditorType:ComboBox;
		
		public var item_merge_from:TextInput;
		public var item_merge_to:TextInput;
		
		public var delegate:GameDelegate;
		
		private var bInSearch:Boolean;
		private var searchType:String;
		private var searchPattern:String;
		private var logId:String = '-1'; 	

		private function onDataChanged(event:CollectionEvent):void
		{
			var item:Object;
			var updated:Object;
			var i:int;

			if(event.kind == CollectionEventKind.UPDATE)
			{
				for(i = 0; i <event.items.length; i++)
				{
					item = event.items[i];
					if ( item.property == 'selected' || item.property == 'id' || item.property == 'download')
						continue;

					updated = new Object;
					updated.id = item.source.id;
					updated.property = item.property;
					updated.value = item.source[item.property];
		trace("update......", updated.value);			
					LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.GAME, LogUtil.UPDATE, updated, '', '', true);
					delegate.updateGame(updated);
				}
			}
		}
		
		public function GameBasicClass()
		{
        	delegate = new GameDelegate(this);
        	delegate.getConfigs();
			delegate.getCountsReadyOpen();
			this.page = 0;
		}
		
		public function getConfigsResult(result:Object, token:Object = null):void
		{
			//delegate.getGames(this.page);
			result = result.result;
			
			//编辑类型
			this.editorTypesSrc = <root />;
			for each ( var a:Object in result.editorTypes )
			{
				var editorType:XML = <type></type>;
				editorType.@id = a.id;
				editorType.@name = a.name;
				this.editorTypesSrc.appendChild(editorType);
			}
			this.editorTypes = new XMLListCollection(this.editorTypesSrc.type);
			
			//题材分类
			this.contentTypesSrc = <root />;
			for each ( var b:Object in result.contentTypes )
			{
				var contentType:XML = <type></type>;
				contentType.@id = b.id;
				contentType.@name = b.name;
				this.contentTypesSrc.appendChild(contentType);
			}
			this.contentTypes = new XMLListCollection(this.contentTypesSrc.type);
			
			//画面类型
			this.screenTypesSrc = <root />;
			for each ( var c:Object in result.screenTypes )
			{
				var screenType:XML = <type></type>;
				screenType.@id = c.id;
				screenType.@name = c.name;
				if(c.name == '所有')
				{
					screenType.@name = '';
				}
				this.screenTypesSrc.appendChild(screenType);
			}
			this.screenTypes = new XMLListCollection(this.screenTypesSrc.type);
			
			//战斗类型
			this.fightTypesSrc = <root />;
			for each ( var d:Object in result.fightTypes )
			{
				var fightType:XML = <type></type>;
				fightType.@id = d.id;
				fightType.@name = d.name;
				if(d.name == '所有')
				{
					fightType.@name = '';
				}
				this.fightTypesSrc.appendChild(fightType);
			}
			this.fightTypes = new XMLListCollection(this.fightTypesSrc.type);		
			
			//付款类型
			this.payTypesSrc = <root />;
			for each ( var e:Object in result.payTypes )
			{
				var payType:XML = <type></type>;
				payType.@id = e.id;
				payType.@name = e.name;
				if(e.name == '所有')
				{
					payType.@name = '';
				}
				this.payTypesSrc.appendChild(payType);
			}
			this.payTypes = new XMLListCollection(this.payTypesSrc.type);	
			
			//游戏国别
			this.countrysSrc = <root />;
			for each ( var f:Object in result.countrys )
			{
				var country:XML = <type></type>;
				country.@id = f.id;
				country.@name = f.name;
				if(f.name == '所有')
				{
					country.@name = '';
				}
				this.countrysSrc.appendChild(country);
			}
			this.countrys = new XMLListCollection(this.countrysSrc.type);	
			
			
			//游戏类型
			this.gameTypesSrc = <root />;
			//var tary:Array = new Array;
			for each ( var g:Object in result.gameTypes )
			{
				if(g.name != '所有')
				{
					var gameType:XML = <type></type>;
					gameType.@id = g.id;
					gameType.@name = g.name;	
					this.gameTypesSrc.appendChild(gameType);				
				}
			}
			this.gameTypes = new XMLListCollection(this.gameTypesSrc.type);	
			
			// 新游戏类型
			this.newGameTypesSrc = <root />;
			for each(var h:Object in result.newType)
			{
				var ngt:XML = <type></type>;
				ngt.@id = h.id;
				ngt.@name = h.name;
				if(h.name == "所有")
				{
					ngt.@name = "";
				}
				this.newGameTypesSrc.appendChild(ngt);
			}
			this.newGameTypes = new XMLListCollection(this.newGameTypesSrc.type);
				
			
			this.pageVolume = result.gamePageVolume;
		}

		public function goto(evt:MouseEvent):void
		{
			var page:int = LinkButton(evt.currentTarget).data.page;
			this.getPage(page);
		}
		
		public function getGamesResult(result:Object, token:Object = null):void
		{
			result = result.result;
			
			prepareData(result.games as Array);
			
			this.games = new ArrayCollection(result.games);
			this.page = result.page;
			this.pagecnt = result.pagecnt;
			
			this.makePageIndices();			
			
			this.games.addEventListener(CollectionEvent.COLLECTION_CHANGE,onDataChanged);
		}
		
		private function prepareData(datas:Array):void
		{
			for each ( var data:Object in datas)
			{
				if(data.gameType)
				{
					var strArray:Array = new Array;
					for each (var gt:Object in data.gameType)		
					{
						strArray.push(gt);
					}
					data['gameType'] = strArray.join(',');		
				}
			}
		}
		
		private function makePageIndices():void
		{
			var a:Array = new Array();
			a.push({page:0,desc:'首页'});			
			a.push({page:page-1,desc:'前一页'});			
			a.push({page:page+1,desc:'后一页'});
			a.push({page:pagecnt-1,desc:'尾页'});
			this.pageIndices = a;
		}
		
		public function editorTypeLabel(item:Object, column:DataGridColumn):String
		{
			if ( this.editorTypesSrc )
				return this.editorTypesSrc.type.(@id==item[column.dataField]).@name;
			else
				return '';
		}             		
		
		public function contentTypeLabel(item:Object, column:DataGridColumn):String
		{
			if ( this.contentTypesSrc )
				return this.contentTypesSrc.type.(@id==item[column.dataField]).@name;
			else
				return '';
		}
		
		public function screenTypeLabel(item:Object, column:DataGridColumn):String
		{
			if( this.screenTypesSrc )
			{
				return this.screenTypesSrc.type.(@id==item[column.dataField]).@name;
			}
			else
			{
				return '';
			}
		} 
		
		public function fightTypeLable(item:Object, column:DataGridColumn):String
		{
			if( this.fightTypesSrc )
			{
				return this.fightTypesSrc.type.(@id==item[column.dataField]).@name;
			}
			else
			{
				return '';
			}
		} 
		
		public function payTypeLable(item:Object, column:DataGridColumn):String
		{
			if( this.payTypesSrc )
			{
				return this.payTypesSrc.type.(@id==item[column.dataField]).@name;
			}
			else
			{
				return '';
			}
		} 
		
		public function newGameTypeLabel(item:Object, column:DataGridColumn):String
		{
			if(this.newGameTypesSrc)
			{
				return this.newGameTypesSrc.type.(@id==item[column.dataField]).@name;
			}
			else
			{
				return "";
			}
		}
		
		public function countryLable(item:Object, column:DataGridColumn):String
		{
			if( this.countrysSrc )
			{
				return this.countrysSrc.type.(@id==item[column.dataField]).@name;
			}
			else
			{
				return '';
			}
		}
		
		public function gameTypeLable(item:Object, column:DataGridColumn):String
		{
			if( this.gameTypesSrc )
			{
				//return this.gameTypesSrc.type.(@id==item[column.dataField]).@name;
				var str:String = '';
				if(item.gameType != '-1')
				{
					var ary:Array = String(item.gameType).split(',');
					for each(var it:String in ary)
					{
						str += this.gameTypesSrc.type.(@id==it).@name + ',';
					}
				}
				return str.substr(0, str.length - 1);
			}
			else
			{
				return '';
			}
		}			
		
        public function clickHandler(event:ItemClickEvent):void 
        {
        	if ( event.index == 0 ) // add game
        	{
        		LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.GAME, LogUtil.ADD, '添加新游戏', '', '', true);
        		this.delegate.addGame();	
        	}
        	else if ( event.index == 1 ) // select all
        	{
				for each ( var a:Object in this.games )
				{
					a.selected = true;
				}
				
	            dispatchEvent(PropertyChangeEvent.createUpdateEvent
	            	(this,'games',null,this.games));
        	}
        	else if ( event.index == 2 ) // deselect all
        	{
				for each ( var a1:Object in this.games )
				{
					a1.selected = false;
				}
				
	            dispatchEvent(PropertyChangeEvent.createUpdateEvent
	            	(this,'games',null,this.games));
        	}	
        	else if ( event.index == 3 ) // del selected
        	{
        		var ids:Array = new Array;
        		
				for each ( var a2:Object in this.games )
				{
					if ( a2.selected )
					{
						ids.push(a2.id);
						a2.selected = false;
					}
				}
				
				if ( ids.length )
				{
		            dispatchEvent(PropertyChangeEvent.createUpdateEvent
		            	(this,'games',null,this.games));
	        		
	        		LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.GAME, LogUtil.DEL, ids.toString(), '', '', true);
	        		this.delegate.removeGames(this.page,ids);
	   			}	
        	}
        }
		
		public function linkto(evt:MouseEvent):void
		{
			navigateToURL(new URLRequest(HBox(LinkedLabel(evt.currentTarget).parent).data.thumbFileName),"_blank");
		}
		
		public function upload(evt:MouseEvent):void
		{
            var display:IFlexDisplayObject = PopUpManager.createPopUp(this,FileUpload,true);
            PopUpManager.bringToFront(display);
            PopUpManager.centerPopUp(display);
			
            FileUpload(display).uploadUrl = 'http://www.aipai.com/app/admin/service/upload/uploadgamethumb.php';
            FileUpload(display).variables.gameId = HBox(LinkedLabel(evt.currentTarget).parent).data.id;
			FileUpload(display).addEventListener('uploadComplete',function(evt:Event):void{Alert.show('文件上传成功!', '提示')});
			FileUpload(display).addEventListener('uploadIOError',function(evt:Event):void{Alert.show('IO错误!', '提示')});
			FileUpload(display).addEventListener('uploadSecurityError',function(evt:Event):void{Alert.show('安全错误!', '提示')});
		}
		
		public function addGameResult(result:Object, token:Object = null):void
		{
			result = result.result;
			
			this.games = new ArrayCollection(result.games);
			this.page = result.page;
			this.pagecnt = result.pagecnt;

			this.makePageIndices();			
			
			this.games.addEventListener(CollectionEvent.COLLECTION_CHANGE,onDataChanged);
		}
						
		public function updateGameResult(result:Object, token:Object = null):void
		{
			result = result.result;
			
			if ( result.code )
			{
				var fault:Fault = new Fault('',result.msg);
				var error:FaultEvent = new FaultEvent('fault',false,true,fault);
				this.fault(error);
				return;
			}
		}

		public function removeGamesResult(result:Object, token:Object = null):void
		{
			result = result.result;
			
			if ( result.code )
			{
				var fault:Fault = new Fault('',result.msg);
				var error:FaultEvent = new FaultEvent('fault',false,true,fault);
				this.fault(error);
				return;
			}
			
			this.games = new ArrayCollection(result.games);
			this.page = result.page;
			this.pagecnt = result.pagecnt;

			this.makePageIndices();			
			
			this.games.addEventListener(CollectionEvent.COLLECTION_CHANGE,onDataChanged);
		}
						
		public function fault(error:FaultEvent,token:Object = null):void
		{
			Alert.show(error.fault.faultString,'error');
		}
		
		public function onBtnMergeCommit():void
		{
			//处理删除	
 			Alert.yesLabel = '确定';
			Alert.noLabel = '取消';
			Alert.buttonWidth = 50;
			Alert.buttonHeight = 20;

			Alert.show('“合并”操作会删除原gameid，确定吗？',
				'提示',Alert.YES | Alert.NO,null,onMergeConfirmed,null,Alert.NO);
			
			return;								
		}
		
        private function onMergeConfirmed(event:CloseEvent):void 
        {
            if (event.detail==Alert.YES)
            {   
            	LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.GAME, LogUtil.ADD, {id1:int(item_merge_from.text),id2:int(item_merge_to.text)}, '' ,'', true);
            	this.delegate.mergeGame(int(item_merge_from.text),int(item_merge_to.text));	       		
            }	
        }
        
		public function mergeGameResult(result:Object, token:Object = null):void
		{
			result = result.result;
			
			if (result.code == 0)
			{
				item_merge_from.text="";
				item_merge_to.text="";			
			}
			else
			{

			}	
			
			Alert.show(result.msg);						
		}		
		
		public function gotoPage(page:String):void
		{
			var p:int = page.length > 0?(int(page)-1):0;
			getPage(p);
		}
		
		public function getPage(page:int=0):void
		{
			if(bInSearch)
			{
				if(searchType=="readyOpen")// 待开放专区分页
				{
					delegate.getUnOpenGames(page);
				}
				else if(searchType=="completeGame")
				{
					delegate.getUnCompleteGames(page);
				}
				else
				{
				     this.delegate.getGamesBySearch(this.searchPattern, this.searchType, page);
				}
			} else {
				this.delegate.getGames(page);
			}
		}
		
		public function onReset():void
		{
			this.bInSearch = false;
			getPage(0);
		}
		
		public function onSearch(type:String, pattern:String):void
		{
			this.bInSearch = true;
			this.searchType = type;
			this.searchPattern = pattern;
			if(type=="readyOpen")
			{
				delegate.getUnOpenGames();
				delegate.getCountsReadyOpen();
			}
			else if(type=="completeGame")
			{
				delegate.getUnCompleteGames();
			}
			else
			{
				getPage(0);
			}
		}
		
		public function getCountsReadyOpenResult(result:Object, token:Object = null):void
		{
			result = result.result;
			if(result > 0)
			{
				label = label.substr(0, 4) + "("+ result +")";
			}
		}
		
	}
}
